import {
  Tree,
  Button,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Col,
  Row,
  Tabs,
  message
} from "antd";
import { DeleteFilled } from "@ant-design/icons";
import React,{ useRef } from "react";
import { useState, useEffect } from "react";
import {
  getClass,
  getSub,
  addSubApi,
  delSubApi,
  getClassContext,
  changeClassDetail,
  addClassDetail,
  addClassApi,
  deleteClassContext,
  deleteClassApi
} from "../../api/user.js";
import { getTeacher, getStu } from "../../api/user";
const { Option } = Select;
const treeData = [
  {
    title: "所有",
    key: "所有",
    children: [
      {
        title: "软件学院",
        key: "软件学院",
      },
      {
        title: "数学学院",
        key: "数学学院",
      },
      {
        title: "文学院",
        key: "文学院",
      },
    ],
  },
];
const items = [
  {
    key: "0",
    label: "必修课",
  },
  {
    key: "1",
    label: "选修课",
  },
];
const Class = () => {
  const inputRef = useRef(null)
  const [isShowContext, setIsShowContext] = useState(0);
  const [isModal, setIsModal] = useState([false, false, false]);
  const [classType, setClassType] = useState(0);
  const [classsub, setClasssub] = useState("所有");
  const [allClass, setAllClass] = useState([]);
  const [classContext, setClassContext] = useState([]);
  const [classDetail, setClassDetail] = useState({ year: 0 });
  const [classTitle, setClassTitle] = useState("");
  const [teacherList, setTeacherList] = useState([]);
  const [stuList, setStuList] = useState([]);
  const [loadings, setLoadings] = useState([false, false]);
  const [selectClass, setSelectClass] = useState(-1);
  const [sub, setSub] = useState([]);
  const [addSub, setAddSub] = useState(false);
  const timeOptions = [
    "第一节课",
    "第二节课",
    "第三节课",
    "第四节课",
    "第五节课",
    "第六节课",
    "第七节课",
    "第八节课",
    "第九节课",
  ];
  const dayOptions = [
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "星期日",
  ];
  const statusOptions = ["未开始", "课程中", "已结课"];
  const typeOptions = ["必修", "选修"];
  useEffect(() => {
    getTeacher().then((res) => {
      console.log(res, "teacher");
      setTeacherList(res.result);
      // setTotal(res.data.totalElements);
    });
    getStu().then((res) => {
      setStuList(res);
      // setTotal(res.data.totalElements);
    });
    getClass({ classsub: "所有", classType }).then((res) => {
      console.log(res, "class");
      setAllClass(res);
    });
    getSub().then(res=>{
      console.log(res, "sub");
      setSub(res.result)
    })
  }, []);
  useEffect(() => {
    form.setFieldsValue(classDetail);
  }, [classDetail]);
  const [form] = Form.useForm();
  //  this.props.form.resetFields();

 
  const changeTab = (activeKey) => {
    console.log("changetab", activeKey);
    setClassType(activeKey);
    getClass({ classsub, classType:activeKey }).then((res) => {
      console.log(res, "class");
      setAllClass(res);
    });
  };
  // const onCheck = (checkedKeys, info) => {
  //   console.log('onCheck', checkedKeys, info);
  // };
  const showContext = (e, item, isShow) => {
    if (isShow) {
      setIsShowContext(0);
    } else {
      setIsShowContext(item.cid);
      setClassTitle(item.cname);
      // getClass({ classsub: classsub, classType:classType }).then((res) => {
      //   console.log(res, "class");
      //   setAllClass(res);
      // });
      getClassContext({ cname: item.cname }).then((res) => {
        setClassContext(res);
        console.log(res, "context");
      });
    }
  };

  const showModal = (e, item, index) => {
    console.log(item, "setClassDetail");
    setClassDetail(item);
    setIsModal((prevState) => {
      const newIsModal = [...prevState]; // 创建一个新的数组副本
      newIsModal[index] = true; // 修改指定索引的值
      return newIsModal; // 返回新的数组
    });
  };

  const deleteContext=(e,item)=>{
    if (window.confirm("您确定要删除此条课程信息吗？")) {
      deleteClassContext(item).then((res) => {
        message.success("删除成功");
        getClassContext({ cname: classTitle }).then((res) => {
          setClassContext(res);
          console.log(res, "context");
        });
      });
    }
   
  }
  const delClass=(e,item)=>{
    if (window.confirm("您确定要删除此条课程信息吗？此条下包含的所有课程都将删除")) {
//       console.log(item)
//       console.log(allClass,'169')
// let allClass2 = allClass.slice();
//       console.log(allClass2,"168")
//       for(let i=0;i<allClass2.length;i++){
//        if(allClass2[i].cname==item.cname){
//          allClass2.splice(i, 1);
//        }
//       }
//       setAllClass(allClass2)
//       console.log(allClass,'175')
      deleteClassApi({classname:item.cname}).then((res) => {
        message.success("删除成功");
       const allClass2=allClass.slice();
       console.log(allClass2,"168")
       for(let i=0;i<allClass2.length;i++){
        if(allClass2[i].cname==item.cname){
          allClass2.splice(i, 1);
        }
       }
       setAllClass(allClass2)
       console.log(allClass,'175')
      });
    }
   
  }
  const addSubject=()=>{
    addSubApi({subname:inputRef.current.input.value}).then((res)=>{
      if(res.status=="ok"){
        getSub().then(res=>{
          setSub(res.result)
          setAddSub(false)
          message.success("新增成功！")
        })
      }
    else{
      message.error(res.result)
    }
    })
    console.log(inputRef.current.input.value)
  }
  const delSubject=(e,item)=>{
    if (window.confirm("您确定要删除本学院吗，学院中所有课程都将被删除")){
      delSubApi({subname:item.subname}).then(()=>{
        getSub().then(res=>{
          setSub(res.result)
          setAddSub(false)
          getClass({ classsub, classType }).then((res) => {
            console.log(res, "class");
            setAllClass(res);
            message.success("删除成功！")
          });
          
        })
      })
    }
    
  }



  
  const handleCancel = (e, index) => {
    setIsModal((prevState) => {
      const newIsModal = [...prevState]; // 创建一个新的数组副本
      newIsModal[index] = false; // 修改指定索引的值
      return newIsModal; // 返回新的数组
    });
    console.log(isModal, index);
  };
  // setIsModal([false,false]);
  const onFinish = (values, index) => {
    let isload = loadings;
    isload[index] = true;
    setLoadings(isload);
    changeClassDetail({
      newClassDetail: values,
      classDetail: classDetail,
    }).then((res1) => {
      getClassContext({ cname: classTitle }).then((res) => {
        setClassContext(res);
        console.log(res, "context");
      });
      alert("修改成功");
      isload[index] = false;
      setLoadings(isload);
      setIsModal([false, false, false]);
      console.log(values);
    });
    setClassDetail(values);
    // let classContext2=classContext
  };

  // const handleCancel = (e,index) => {

  //   setIsModal((prevState) => {
  //     const newIsModal = [...prevState]; // 创建一个新的数组副本
  //     newIsModal[index] = false; // 修改指定索引的值
  //     return newIsModal; // 返回新的数组
  //   });
  //   console.log(isModal,index)
  // };
  // setIsModal([false,false]);
  const addClassContext = (values, index) => {
    let isload = loadings;
    isload[index] = true;
    setLoadings(isload);
    addClassDetail({ newClassDetail: values, title: classTitle }).then(
      (res1) => {
        if(res1.status=="ok"){
          getClassContext({ cname: classTitle }).then((res) => {
            setClassContext(res);
            console.log(res, "context");
          });
          alert("新增成功");
          isload[index] = false;
          
          setIsModal([false, false, false]);
          console.log(values);
        }
       else{
        message.error(res1.err)
       }
       setLoadings(isload);
      }
    );
    setClassDetail(values);
    // let classContext2=classContext

    // form.resetFields();
  };
  const addClass = (values, index) => {
    let isload = loadings;
    isload[index] = true;
    setLoadings(isload);
    addClassApi(values).then(res=>{
      console.log(res)
      if(res.status=="ok"){
        getClass({ classsub, classType }).then((res) => {
          console.log(res, "class");
          setAllClass(res);
        });
        message.success(res.result)
        setIsModal([false, false, false]);
        console.log(values);
      }
      else{
        message.error(res.result)
      }
      
    })
    // isload[index] = false
    // setLoadings(isload)
   

    // setClassDetail(values);
    // let classContext2=classContext

    // form.resetFields();
  };
  const selectedClass = (e, index, item) => {
    setSelectClass(index);
    setClasssub(item.subname);
    console.log(item)
    getClass({ classsub: item.subname, classType }).then((res) => {
      console.log(res, "class");
      setAllClass(res);
    });
    // console.log(item);
  };
  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        display: "flex",
        justifyContent: "space-around",
      }}
    >
      <div style={{ width: "15%", height: "100%" }}>
        {sub.map((item, index) => {
          return (
            <div
              style={{
                width: "100%",
                display: "flex",
                justifyContent: "space-around",
                alignItems: "center",
                font: "17px bolder",
                borderRadius: "10px",
                margin: "10px",
                backgroundColor: selectClass == index ? "#A5E9FF" : "#fff",
              }}
              key={"tree" + index}
            >
              <a
                onClick={(e) => selectedClass(e, index, item)}
                style={{ color: "black" }}
              >
                {" "}
                <span> {item.subname}</span>
              </a>
              <Button
                danger
                type="text"
                onClick={(e) => delSubject(e, item)}
              >
                <DeleteFilled />
              </Button>
            </div>
          );
        })}

       {(!addSub) && <Button onClick={e=>setAddSub(true)} style={{ width: "100%" }} type="primary">
          新增学院
        </Button>}
        {addSub &&<Input ref={inputRef} style={{ width: "100%" }}></Input>}
      { addSub && <div
          style={{
            width: "100%",
            display: "flex",
            justifyContent: "space-between",
            marginTop:"10px"
          }}
        >
          <Button  onClick={e=>setAddSub(false)} style={{ width: "45%" }}>
            取消
          </Button>
          <Button onClick={addSubject} style={{ width: "45%" }} type="primary">
            确定
          </Button>
        </div>}
      </div>
      <div style={{ backgroundColor: "#fff", width: "80%" }}>
        <Tabs
          style={{ margin: "auto", width: "90%" }}
          defaultActiveKey="0"
          items={items}
          onChange={changeTab}
        />
        <div style={{ overflow: "auto", height: "70%" }}>
          {allClass.map((item, index) => {
            return (
              <div
                key={item.cid}
                style={{
                  border: "solid #ccc",
                  borderRadius: "12px",
                  margin: "auto",
                  width: "90%",
                  padding: "10px",
                  marginBottom: "10px",
                }}
              >
                <div
                  style={{ display: "flex", justifyContent: "space-between" }}
                >
                  <div>
                    {item.cname}
                    <Button
                      type="link"
                      onClick={(e) =>
                        showContext(e, item, isShowContext == item.cid)
                      }
                    >
                      {isShowContext == item.cid ? "收回" : "展开"}
                    </Button>
                  </div>
                  <Button
                    danger
                    type="text"
                    onClick={(e) =>
                      delClass(e, item)
                    }
                  >
                    <DeleteFilled />
                  </Button>
                </div>
                {isShowContext == item.cid && (
                  <div>
                    {classContext.map((item1, index1) => {
                      return (
                        <div
                          key={"context" + index1}
                          style={{
                            border: "2px",
                            borderBottomStyle: "solid",
                            width: "100%",
                            marginBottom: "10px",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "space-around",
                          }}
                        >
                          {/* <span>1</span>/ */}
                          <span>学年：{item1.year}</span>
                          <span>
                            {dayOptions[item1.day - 1] +
                              " " +
                              timeOptions[item1.time - 1]}
                          </span>
                          <span>
                            {teacherList.map(
                              (item2) =>
                                item2.tid == item1.tid && (
                                  <div key={"teacherL" + item2.tid}>
                                    {item2.tname}
                                  </div>
                                )
                            )}
                          </span>
                          <span>地点：{item1.address}</span>
                          <span>
                            {item1.status == 0 && (
                              <Tag color="cyan">未开始</Tag>
                            )}
                            {item1.status == 1 && (
                              <Tag color="blue">课程中</Tag>
                            )}
                            {item1.status == 2 && (
                              <Tag color="green">已结课</Tag>
                            )}
                          </span>
                          <span>
                            <Button
                              type="link"
                              onClick={(e) => showModal(e, item1, 0)}
                            >
                              详情
                            </Button>
                            <Button
                              type="danger"
                              onClick={(e) =>
                                deleteContext(e,item1)
                              }
                            >
                              删除
                            </Button>
                          </span>
                        </div>
                      );
                    })}
                    <div>
                      <Button
                        type="primary"
                        onClick={(e) => showModal(e, {}, 1)}
                      >
                        课程新增
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
        <div
          style={{
            margin: "auto",
            width: "90%",
            padding: "10px",
            marginBottom: "10px",
          }}
        >
          <Button type="primary" onClick={(e) => showModal(e, {}, 2)}>
            新增课程
          </Button>
        </div>
      </div>
      <Modal
        title="课程修改"
        open={isModal[0]}
        footer={null}
        onCancel={(e) => {
          handleCancel(e, 0);
        }}
      >
        <Form
          name="basic"
          form={form}
          layout="vertical"
          initialValues={classDetail}
          // style={{ width: 400, margin: '50px auto' }}
          onFinish={(values) => onFinish(values, 0)}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col className="gutter-row" span={12}>
              <Form.Item label="课程名称" name="classname">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="学年"
                name="year"
                rules={[
                  {
                    required: true,
                    message: "请输入所属学年",
                  },
                ]}
              >
                <Input disabled={classDetail.status} />
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="教师"
                name="tid"
                rules={[
                  {
                    required: true,
                    message: "请选择上课教师",
                  },
                ]}
              >
                <Select
                  disabled={classDetail.status}
                  placeholder="请选择上课教师"
                >
                  {teacherList.map((item) => (
                    <Option key={"teacher" + item.tid} value={item.tid}>
                      {item.tname}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课日期"
                name="day"
                rules={[
                  {
                    required: true,
                    message: "请选择上课日期",
                  },
                ]}
              >
                <Select
                  disabled={classDetail.status}
                  placeholder="请选择上课日期"
                >
                  {dayOptions.map((item, index) => (
                    <Option key={"day" + index} value={index + 1}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课时间"
                name="time"
                rules={[
                  {
                    required: true,
                    message: "请选择上课时间",
                  },
                ]}
              >
                <Select
                  disabled={classDetail.status}
                  placeholder="请选择上课时间"
                >
                  {timeOptions.map((item, index) => (
                    <Option key={"time" + index} value={index + 1}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="课程状态"
                name="status"
                rules={[
                  {
                    required: true,
                    message: "请选择课程状态",
                  },
                ]}
              >
                <Select placeholder="请选择课程状态">
                  {statusOptions.map((item, index) => (
                    <Option key={"status" + index} value={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课地址"
                name="address"
                rules={[
                  {
                    required: true,
                    message: "请输入上课地址",
                  },
                ]}
              >
                <Input disabled={classDetail.status} />
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="学生"
                name="student"
                rules={[
                  {
                    required: true,
                    message: "请选择上课学生",
                  },
                ]}
              >
                <Select
                  disabled={classDetail.status}
                  mode="multiple"
                  placeholder="请选择上课教师"
                >
                  {stuList.map((item) => (
                    <Option key={"stu" + item.sid} value={item.sid}>
                      {item.sname}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课人数"
                name="allNum"
                rules={[
                  {
                    required: true,
                    message: "请输入上课人数",
                  },
                ]}
              >
                <Input disabled={classDetail.status}  />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Button
              loading={loadings[0]}
              block
              shape="round"
              type="primary"
              htmlType="submit"
            >
              确认修改
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={classTitle + " 课程新增"}
        open={isModal[1]}
        footer={null}
        destroyOnClose={true}
        onCancel={(e) => {
          handleCancel(e, 1);
        }}
      >
        <Form
          name="basic"
          layout="vertical"
          onFinish={(values) => addClassContext(values, 1)}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="学年"
                name="year"
                rules={[
                  {
                    required: true,
                    message: "请输入所属学年",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="教师"
                name="tid"
                rules={[
                  {
                    required: true,
                    message: "请选择上课教师",
                  },
                ]}
              >
                <Select placeholder="请选择上课教师">
                  {teacherList.map((item) => (
                    <Option key={"teacher" + item.tid} value={item.tid}>
                      {item.tname}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课日期"
                name="day"
                rules={[
                  {
                    required: true,
                    message: "请选择上课日期",
                  },
                ]}
              >
                <Select placeholder="请选择上课日期">
                  {dayOptions.map((item, index) => (
                    <Option key={"day" + index} value={index + 1}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课时间"
                name="time"
                rules={[
                  {
                    required: true,
                    message: "请选择上课时间",
                  },
                ]}
              >
                <Select placeholder="请选择上课时间">
                  {timeOptions.map((item, index) => (
                    <Option key={"time" + index} value={index + 1}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="课程状态"
                name="status"
                rules={[
                  {
                    required: true,
                    message: "请选择课程状态",
                  },
                ]}
              >
                <Select placeholder="请选择课程状态">
                  {statusOptions.map((item, index) => (
                    <Option key={"status" + index} value={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课地址"
                name="address"
                rules={[
                  {
                    required: true,
                    message: "请输入上课地址",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="学生"
                name="student"
                rules={[
                  {
                    required: true,
                    message: "请选择上课学生",
                  },
                ]}
              >
                <Select mode="multiple" placeholder="请选择上课学生">
                  {stuList.map((item) => (
                    <Option key={"stu" + item.sid} value={item.sid}>
                      {item.sname}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="上课人数"
                name="allNum"
                rules={[
                  {
                    required: true,
                    message: "请输入上课人数",
                  },
                ]}
              >
                <Input type="number" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Button
              loading={loadings[0]}
              block
              shape="round"
              type="primary"
              htmlType="submit"
            >
              确认新增
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={"新增课程"}
        open={isModal[2]}
        footer={null}
        destroyOnClose={true}
        onCancel={(e) => {
          handleCancel(e, 2);
        }}
      >
        <Form
          name="basic"
          layout="vertical"
          onFinish={(values) => addClass(values, 1)}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col className="gutter-row" span={24}>
              <Form.Item
                label="课程名称"
                name="cname"
                rules={[
                  {
                    required: true,
                    message: "请输入课程名称",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>

            <Col className="gutter-row" span={12}>
              <Form.Item
                label="所属学院"
                name="csub"
                rules={[
                  {
                    required: true,
                    message: "请选择所属学院",
                  },
                ]}
              >
                <Select placeholder="请选择所属学院">
                  {sub.map((item, index) => (
                    <Option key={"sub" + index} value={item.subname}>
                      {item.subname}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="课程类别"
                name="ctype"
                rules={[
                  {
                    required: true,
                    message: "请选择课程类别",
                  },
                ]}
              >
                <Select placeholder="请选择课程类别">
                  {typeOptions.map((item, index) => (
                    <Option key={"type" + index} value={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Button
              loading={loadings[0]}
              block
              shape="round"
              type="primary"
              htmlType="submit"
            >
              确认新增
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default Class;
